package com.quasar.hpatient.module.home_inspection;

import android.graphics.Color;
import android.os.SystemClock;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.comm_album.AlbumPhotoBean;
import com.quasar.hpatient.bean.home_inspection.CalendarBean;
import com.quasar.hpatient.bean.home_inspection.InspectionBean;
import com.quasar.hpatient.dialog.CalendarDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.base.frame.OnModelChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.context.BaseConstant;
import lib.quasar.recycler.BaseCommonAdapter;
import lib.quasar.recycler.BaseCommonMultAdapter;
import lib.quasar.recycler.decoration.SpaceDecoration;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.recycler.model.MultModel;
import lib.quasar.util.DimenUtil;
import lib.quasar.util.ToastUtil;
import lib.quasar.widget.edit.AlterEditText;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * description: 化验记录
 * created by kalu on 2018/4/10 10:26
 */
public class HomeInspectionPresenter implements BasePresenter {

    public static final String INSPECTION_NULL = "INSPECTION_NULL";
    public static final String INSPECTION_ONLY_PICTURE = "INSPECTION_ONLY_PICTURE";
    public static final String INSPECTION_EXIST_DATA = "INSPECTION_EXIST_DATA";

    private final ArrayList<InspectionBean.DoctorBean> mDoctor = new ArrayList<>();
    private final ArrayList<AlbumPhotoBean> mPhoto = new ArrayList<>();
    private final ArrayList<InspectionBean.ItemBean> mDatas = new ArrayList<>();

    void initList(final HomeInspectionView view, RecyclerView recycler) {

        if (null == view || null == recycler)
            return;

        recycler.setTag(INSPECTION_NULL);
        final BaseCommonMultAdapter<InspectionBean.ItemBean> adapter = new BaseCommonMultAdapter<InspectionBean.ItemBean>(mDatas) {

            @Override
            protected void onRoll(RecyclerView recycler, int itemHeight, int rollHeight, int rollState, int fistVisablePosition, int lastVisablePosition) {
                super.onRoll(recycler, itemHeight, rollHeight, rollState, fistVisablePosition, lastVisablePosition);

                final int end = Math.min(lastVisablePosition, mDatas.size());
                for (int i = fistVisablePosition; i < end; i++) {

                    final InspectionBean.ItemBean model = mDatas.get(i);
                    if (model.getMultType() != MultModel.TYPE_2 || model.isUrine() || model.isStable() || !model.isLessthanMins())
                        continue;

                    view.toast("请输入正确结果：" + model.getItem_name());
                    model.setItem_value("");
                    final int position = i + 1;
                    recycler.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 0, 0, 0));
                    recycler.getAdapter().notifyItemChanged(position);
                    break;
                }
            }

            @Override
            protected void onMult() {
                addMult(MultModel.TYPE_0, R.layout.activity_home_inspection_type_menu);
                addMult(MultModel.TYPE_1, R.layout.activity_home_inspection_type_null);
                addMult(MultModel.TYPE_2, R.layout.activity_home_inspection_type_normal);
            }

            @Override
            protected void onNext(final RecyclerHolder holder, final InspectionBean.ItemBean model, final int position) {

                switch (model.getMultType()) {
                    case MultModel.TYPE_0:

                        view.setText(holder, R.id.inspection_menu, model.getInspection_name());

                        // 增加
                        holder.setOnClickListener(R.id.inspection_menu_add, v -> view.showAdd(position, model.getInspection_name(), model.getGroupid()));

                        // 展开
                        holder.setOnClickListener(R.id.activity_home_report_child_type5_all, v -> {
                            String inspectionname = model.getInspection_name();
                            if (TextUtils.isEmpty(inspectionname)) return;
                            for (int i = position + 1; i < mDatas.size(); i++) {
                                InspectionBean.ItemBean temp = mDatas.get(i);
                                String inspectionname1 = temp.getInspection_name();
                                if (!inspectionname.equals(inspectionname1)) break;
                                else {
                                    String attribute = temp.getAttribute();
//                                    if (!"0".equals(attribute)) continue;
//                                    temp.setAttribute("3");
                                    if ("0".equals(attribute))
                                        temp.setAttribute("3");
                                    if ("4".equals(attribute))
                                        temp.setAttribute("2");
                                }
                            }
                            view.refreshList(recycler);
                        });

                        // 隐藏
                        holder.setOnClickListener(R.id.activity_home_report_child_type5_fold, v -> {
                            String inspectionname = model.getInspection_name();
                            if (TextUtils.isEmpty(inspectionname)) return;
                            for (int i = position + 1; i < mDatas.size(); i++) {
                                InspectionBean.ItemBean temp = mDatas.get(i);
                                String inspectionname1 = temp.getInspection_name();
                                if (!inspectionname.equals(inspectionname1)) break;
                                else {
                                    String attribute = temp.getAttribute();
                                    //如果不是自定义大项就隐藏
                                    if (!"3".equals(attribute)) {
//                                        if ("2".equals(attribute) && "".equals(temp.getItem_value())) {
//                                            temp.setAttribute("0");
//                                        }
                                        continue;
                                    }
                                    temp.setAttribute("0");
                                }
                            }
                            view.refreshList(recycler);
                        });
                        break;
                    case MultModel.TYPE_2:

                        final AlterEditText unit = holder.getView(R.id.inspection_unit);
                        unit.setModelText(model.getDose_name());
                        unit.setOnInputChangeListener((input, isModelChange, isMax) -> {
                            if (isModelChange) {
                                recycler.setTag(INSPECTION_EXIST_DATA);
                            }
                            model.setDose_name(input);
                        });

                        view.setText(holder, R.id.inspection_name, model.getItem_name());
                        view.setTextColor(holder, R.id.inspection_name, model.getNameColor());
                        view.setText(holder, R.id.inspection_simple, model.getStandard_value());
                        view.setText(holder, R.id.inspection_unit, model.getDose_name());

                        final AlterEditText edit = holder.getView(R.id.inspection_value);
                        edit.setModelText(model.getItem_value());

                        // 定性(禁止输入)
                        if (model.isStable()) {

                            edit.setInputType(InputType.TYPE_NULL);
                            edit.setCursorVisible(false);
                            edit.setFocusable(false);
                            edit.setFocusableInTouchMode(false);
                            edit.setMaxInput(-1);
                            edit.setMaxWarning(-1);
                            edit.setMinWarning(-1);

                            edit.setOnInputChangeListener(null);
                            edit.setOnClickListener(v -> view.showQualitative(position));

                            view.setText(edit, model.getItem_value());
                            view.setTextColor(edit, model.getNormalColor());

                        }
                        // 其它(正常输入)
                        else {

                            edit.setCursorVisible(true);
                            edit.setFocusable(true);
                            edit.setFocusableInTouchMode(true);

                            // 尿液
                            if (model.isUrine()) {

                                edit.setInputType(InputType.TYPE_CLASS_TEXT);
                                edit.setHanziFilter(4);
                                edit.setMaxInput(-1);
                                edit.setMaxWarning(-1);
                                edit.setMinWarning(-1);

                                edit.setOnClickListener(null);
                                edit.setOnInputChangeListener((input, isModelChange, isMax) -> {
                                    if (isModelChange) {
                                        recycler.setTag(INSPECTION_EXIST_DATA);
                                    }
                                    model.setItem_value(input);
                                });

                                view.setText(edit, model.getItem_value());
                                view.setTextColor(edit, model.getNormalColor());
                            }
                            // 普通
                            else {

                                edit.setInputType(8194);
                                edit.setNumberFilter(3, 7);
                                edit.setMaxInput(model.getInputMax());
                                edit.setMaxWarning(model.getWarningMax());
                                edit.setMinWarning(model.getWarningMin());

                                edit.setOnClickListener(null);
                                edit.setOnInputChangeListener((input, isModelChange, isMax) -> {
                                    if (isModelChange) {
                                        recycler.setTag(INSPECTION_EXIST_DATA);
                                    }
                                    model.setItem_value(input);
                                });

                                view.setText(edit, model.getItem_value());
                                view.setTextColor(edit, model.getInputColor());
                            }
                        }

                        // 1.名字
                        holder.setOnClickListener(R.id.inspection_name, v -> view.goSingle(model.getItem_name(), model.getDose_name()));

                        // 2.参考值
                        holder.setOnClickListener(R.id.inspection_simple, v -> {
                            final String temp = model.getStandard_value();
                            if (TextUtils.isEmpty(temp)) {
                                view.showInput(position, "", "");
                            } else {
                                final String[] split = temp.split("-");
                                if (split.length != 2) {
                                    view.showInput(position, "", "");
                                } else {
                                    view.showInput(position, split[0], split[1]);
                                }
                            }
                        });

                        // 3.单位


                        // 4.长按
                        holder.setOnLongClickListener(v -> {
                            if (model.canDelete()) {
                                view.deleteModel(position);
                            } else {
                                ToastUtil.showToast("系统项不可以删除");
                            }
                            return true;
                        }, R.id.inspection_name, R.id.inspection_value, R.id.inspection_simple, R.id.inspection_unit);
                        break;
                }
            }
        };

        // 头部
        final View head = LayoutInflater.from(BaseApp.getContext()).inflate(R.layout.activity_home_inspection_type_head, null);
        head.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
        adapter.addHead(head);
        // 日期
        final TextView time = head.findViewById(R.id.home_inspection_time);
        time.setText(getCalendar());
        // 图片
        final RecyclerView photo = head.findViewById(R.id.home_inspection_picture);
        initPhoto(photo, view);

        //前一次
        head.findViewById(R.id.home_inspection_preview).setOnClickListener(v -> inspectionList(view, recycler, false, true));
        //后一次
        head.findViewById(R.id.home_inspection_next).setOnClickListener(v -> inspectionList(view, recycler, true, false));
        //日期
        head.findViewById(R.id.home_inspection_time).setOnClickListener(v -> view.showCalendar());
        //脚部
        final View foot = LayoutInflater.from(BaseApp.getContext()).inflate(R.layout.activity_home_inspection_type_foot, null);
        foot.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dp2px(70)));
        adapter.addFoot(foot);
        foot.findViewById(R.id.home_inspection_type_foot).setOnClickListener(v -> view.showAdd(-1, "", ""));
        // 空布局
        adapter.setNullView(BaseApp.getContext(), R.layout.layout_recycler_loading);
        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        view.setRecycler(recycler, adapter, manager);
    }

    void inspectionList(HomeInspectionView view, RecyclerView recycler, boolean next, boolean preview) {

        if (null == view || null == recycler) return;

        final String time = getTime(view, recycler);
        if (TextUtils.isEmpty(time)) return;

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.INSPECTION_DATE, getDate(time));

        final String datatype = (!next && !preview ? HttpParams.DATA_TYPE_4_8 : (preview ? HttpParams.DATA_TYPE_4_2 : HttpParams.DATA_TYPE_4_3));
        final RequestBody params = createParams(map, datatype);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().assayList(params);

        request(observable, new OnModelAcceptChangeListener<InspectionBean>() {

            @Override
            public void modelSucc(InspectionBean result) {
                if (null == result)
                    return;

                final String time1 = result.getInspection_date();
                final String time2 = result.getAsk_record_date();

                final boolean ok = (!TextUtils.isEmpty(time1) && !TextUtils.isEmpty(time2) && time1.equals(time2));
                if (!ok && (next || preview)) {
                    if (next) {
                        view.toast("后一次, 无数据");
                    } else if (preview) {
                        view.toast("前一次, 无数据");
                    }
                }

                // 日期
                setTime(view, recycler, time2);

                // 我的医生
                final List<InspectionBean.DoctorBean> json_doctor = result.getJson_doctor();
                if (null != json_doctor && json_doctor.size() > 0) {
                    mDoctor.clear();
                    mDoctor.addAll(json_doctor);
                }

                // 建议
                final List<InspectionBean.SuggestBean> json_advise = result.getJson_inspection_advise();
                setSuggest(view, recycler, ok ? json_advise : null);
                // 印章
                setTimestap(view, recycler, ok ? result.isDiagnose() : false);
                // 事件
                final List<InspectionBean.EventBean> json_event = result.getJson_event();
                setEvent(view, recycler, json_event, false);
                // 诊断
                final List<InspectionBean.DiagnoseBean> json_diagnose = result.getJson_inspection_diagnose();
                setDiagnose(view, recycler, json_diagnose);

                // 图片
                final List<AlbumPhotoBean> pictureList = result.getJson_inspection_picture();
                mPhoto.clear();
                if (null != pictureList && !pictureList.isEmpty()) {
                    for (AlbumPhotoBean model : pictureList) {
                        if (model.isAdd()) continue;
                        mPhoto.add(model);
                    }
                }
                final AlbumPhotoBean add = new AlbumPhotoBean();
                add.setPicture(String.valueOf(R.drawable.ic_album_add));
                mPhoto.add(add);
                refreshPhoto(view, recycler);

                // 化验单列表(返回数据不可能为空)
                final List<InspectionBean.ItemBean> inspectionList = result.getJson_inspection_data();
                mDatas.clear();
                if (null != inspectionList && !inspectionList.isEmpty()) {
                    for (int i = 0; i < inspectionList.size(); i++) {
                        final InspectionBean.ItemBean model = inspectionList.get(i);
                        if (!ok) {
                            model.setItem_value("");
                        }
                        mDatas.add(model);
                    }
                }
            }

            @Override
            public void modelComplete() {
                view.refreshList(recycler);
            }
        });
    }

    private final void initPhoto(final RecyclerView recycler, final HomeInspectionView view) {
        if (null == recycler || null == view) return;

        // 适配器
        final BaseCommonAdapter<AlbumPhotoBean> adapter = new BaseCommonAdapter<AlbumPhotoBean>(mPhoto, R.layout.activity_home_inspection_type_picture) {

            @Override
            protected void onNext(RecyclerHolder holder, final AlbumPhotoBean model, final int position) {

                final ImageView image = holder.getView(R.id.activity_home_report_head_child_image);

                if (model.isAdd()) {
                    view.setImage(image, R.drawable.ic_album_add);
                } else {
                    view.setImage(image, model.getUrlLittle());
                }
                image.setOnClickListener(v -> {
                    if (model.isAdd()) {
                        view.goAlbum(mPhoto);
                    } else {
                        if (TextUtils.isEmpty(model.getPicture())) return;
                        final LinkedList<ImageView> list1 = new LinkedList<>();
                        for (int i = 0; i < mPhoto.size(); i++) {
                            list1.add(image);
                        }
                        view.showPhoto(position, mPhoto, mPhoto, list1);
                    }
                });
            }
        };

        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        final SpaceDecoration decoration = new SpaceDecoration(DimenUtil.dp2px(10), Color.TRANSPARENT);
        manager.setOrientation(RecyclerView.HORIZONTAL);
        view.setRecycler(recycler, adapter, manager, decoration);
    }

//    final boolean isPictureNull() {
//        return (null == mPhoto || mPhoto.size() <= 1);
//    }

    final void saveInspection(final HomeInspectionView view, RecyclerView recycler, List<InspectionBean.DoctorBean> list) {

        if (null == view || null == recycler) return;

        final String time = getTime(view, recycler);
        if (TextUtils.isEmpty(time)) {
            view.toast("化验单发生错误");
            return;
        }

        // 循环, 警告值
        String warnSign = "0";
        for (int i = 0; i < mDatas.size(); i++) {

            final InspectionBean.ItemBean model = mDatas.get(i);
            if (!model.isStable() && !model.isUrine() && model.isLessthanMins()) {
                view.toast("请输入正确结果：" + model.getItem_name());
                model.setItem_value("");
                recycler.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 0, 0, 0));
                recycler.getAdapter().notifyItemChanged(i + 1);
                return;
            }

            if (!model.isBig() && !model.isStable() && !model.isUrine()) {
                final String item_value = model.getItem_value();
                if (!TextUtils.isEmpty(item_value) && item_value.endsWith(".")) {
                    model.setItem_value(item_value.substring(0, item_value.length() - 1));
                }
            }

            model.setSortid(String.valueOf(i + 1));

            if ("3".equals(model.getAttribute())) {
                model.setAttribute("0");
            }

            if ("0".equals(warnSign) && model.isWarnings()) {
                warnSign = "1";
            }
        }

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.INSPECTION_DATE, time);
        map.put(HttpParams.JSON_INSPECTION_DATA, mDatas);
        map.put(HttpParams.PATIENT_ID, getPatientId());
        map.put(HttpParams.PATIENT_NAME, getPatientName());
        map.put(HttpParams.DOCTOR_ID, "");
        map.put(HttpParams.EDITOR_TYPE, 2);
        map.put(HttpParams.WARN_SIGN, warnSign);

        final HashMap<String, String> doctorMap = new HashMap<>();
        for (int x = 0; x < list.size(); x++) {
            doctorMap.put("d" + list.get(x).getDoctorid(), list.get(x).getReal_name());
        }
        map.put(HttpParams.JSON_INSPECTION_DOCTORS, doctorMap);

        final LinkedList<AlbumPhotoBean> pictureList = new LinkedList<>();
        pictureList.addAll(mPhoto);
        pictureList.removeLast();
        map.put(HttpParams.JSON_INSPECTION_PICTURE, pictureList);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_47);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveAssayRecord(params);
        request(observable, new OnModelChangeListener() {

            @Override
            public void modelStart() {
                view.beginLoading();
            }

            @Override
            public void modelFail() {
                view.toast("保存化验单失败");
            }

            @Override
            public void modelSucc() {
                recycler.setTag(INSPECTION_NULL);
                view.toast("保存化验单成功");
            }

            @Override
            public void modelComplete() {
                view.closeLoading();
                view.refreshList(recycler);
            }
        });
    }

    void editInspection(final HomeInspectionView view, RecyclerView recycler, String input, int position) {

        if (null == view || null == recycler || TextUtils.isEmpty(input) || position >= mDatas.size())
            return;
        final InspectionBean.ItemBean model = mDatas.get(position);

        final String item_value = model.getItem_value();
        if (input.equals(item_value))
            return;

        model.setItem_value(input);
        view.refreshList(recycler);
        recycler.setTag(INSPECTION_EXIST_DATA);
    }

    void addInspection(HomeInspectionView view, RecyclerView recycler, int position, String groupid,
                       String inspectionName,
                       String itemName,
                       String itemValue,
                       String minValue,
                       String maxValue,
                       String unit) {

        if (TextUtils.isEmpty(inspectionName) || TextUtils.isEmpty(itemName)) {
            view.toast("化验单名称不能为空");
            return;
        }

        try {
            if (!TextUtils.isEmpty(minValue) && !TextUtils.isEmpty(maxValue) && (Float.parseFloat(minValue) >= Float.parseFloat(maxValue))) {
                ToastUtil.showToast("最小参考值不能大于等于最大参考值");
                return;
            }
        } catch (Exception e) {
        }

        if (position != -1 && TextUtils.isEmpty(groupid)) {
            view.toast("化验单信息错误");
            return;
        }

        final int end = mDatas.size();


        for (int i = 0; i < end; i++) {

            final InspectionBean.ItemBean model = mDatas.get(i);

            if ((position == -1) && inspectionName.equals(model.getInspection_name())) {
                view.toast(itemName + "项已存在, 不能重复添加");
                return;
            }

            if (itemName.equals(model.getItem_name())) {
                view.toast(itemName + "项已存在, 不能重复添加");
                return;
            }

        }

        final InspectionBean.ItemBean little = new InspectionBean.ItemBean();
        if (position != -1) {
            little.setInspection_name(inspectionName);
            little.setItem_name(itemName);
            little.setItem_value(itemValue);
            little.setStandard_value((TextUtils.isEmpty(minValue) || TextUtils.isEmpty(maxValue)) ? "" : (minValue + "-" + maxValue));
            little.setDose_name(unit);
            little.setFlag("4");
            little.setAttribute("3");
            little.setBelongto(groupid);
            int maxItemId = getMaxItemId(inspectionName);
            String u = mDatas.get(maxItemId).getItemid();
            little.setItemid(String.valueOf(Integer.parseInt(mDatas.get(getMaxItemId(inspectionName)).getItemid()) + 1));
            little.setSortid(String.valueOf(getMaxItemId(inspectionName) + 1));
            mDatas.add(getMaxItemId(inspectionName) + 1, little);
        } else {
            final InspectionBean.ItemBean big = new InspectionBean.ItemBean();
            big.setGroupid(String.valueOf(getMaxGroupId() + 1));
            big.setAttribute("1");
            big.setFlag("3");
            big.setInspection_name(inspectionName);
            big.setSortid(String.valueOf(mDatas.size()));
            mDatas.add(big);
            little.setInspection_name(inspectionName);
            little.setItem_name(itemName);
            little.setItem_value(itemValue);
            little.setStandard_value(minValue + "-" + maxValue);
            little.setDose_name(unit);
            little.setFlag("4");
            little.setAttribute("3");
            little.setBelongto(String.valueOf(getMaxGroupId() + 1));
            little.setItemid(String.valueOf(1));
            little.setSortid(String.valueOf(mDatas.size()));
            mDatas.add(little);
        }

//        String itemid = "1";
//        int insertPosition = -1;
//        final int end = mDatas.size();
//
//        for (int i = 0; i < end; i++) {
//
//            final ItemBean model = mDatas.get(i);
//
//            // 添加化验项
//            if (position != -1) {
//                if (model.isBig()) continue;
//
//
//            }
//            // 添加化验单
//            else if (inspectionName.equals(model.getInspection_name())) {
//                view.toast(itemName + "项已存在, 不能重复添加");
//                return;
//            }
//
//            if (itemName.equals(model.getItem_name())) {
//                view.toast(itemName + "项已存在, 不能重复添加");
//                return;
//            }
//
//            // 添加化验单, 查找groupid
//            if (position == -1 && model.isBig()) {
//                groupid = model.getGroupid();
//            }
//
//            // 添加化验项, 计算itemid, 插入index
//            if (position != -1 && inspectionName.equals(model.getInspection_name())) {
//                itemid = model.getSortid();
//                insertPosition = i;
//            } else if (position == -1 && inspectionName.equals(model.getInspection_name())) {
//                itemid = model.getSortid();
//            }
//
//            // 重新计算sortid
//            if (!TextUtils.isEmpty(itemid) && i > position && !inspectionName.equals(model.getInspection_name())) {
//                model.setSortid(String.valueOf(Integer.parseInt(model.getSortid()) + (position == -1 ? 2 : 1)));
//            }
//
//            if (i != (end - 1)) continue;
//
//            final ItemBean little = new ItemBean();
//            if (position != -1) {
//                little.setInspection_name(inspectionName);
//                little.setItem_name(itemName);
//                little.setItem_value(itemValue);
//                little.setStandard_value((TextUtils.isEmpty(minValue) || TextUtils.isEmpty(maxValue)) ? "" : (minValue + "-" + maxValue));
//                little.setDose_name(unit);
//                little.setFlag("4");
//                little.setAttribute("2");
//                little.setBelongto(groupid);
//                little.setItemid(String.valueOf(Integer.parseInt(itemid) - position));
//                little.setSortid(String.valueOf(insertPosition + 1));
//                mDatas.add(insertPosition + 1, little);
//            } else {
//                final ItemBean big = new ItemBean();
//                big.setGroupid(groupid);
//                big.setAttribute("2");
//                big.setFlag("3");
//                big.setInspection_name(inspectionName);
//                big.setSortid(String.valueOf(mDatas.size()));
//                mDatas.add(big);
//                little.setInspection_name(inspectionName);
//                little.setItem_name(itemName);
//                little.setItem_value(itemValue);
//                little.setStandard_value(minValue + "-" + maxValue);
//                little.setDose_name(unit);
//                little.setFlag("4");
//                little.setAttribute("2");
//                little.setBelongto(groupid);
//                little.setItemid(String.valueOf(Integer.parseInt(itemid) + 1));
//                little.setSortid(String.valueOf(mDatas.size()));
//                mDatas.add(little);
//            }
//        }

        view.refreshList(recycler);
        recycler.setTag(INSPECTION_EXIST_DATA);
    }


    int getMaxItemId(String inspectionName) {

        int itemId = 0;

        int retPosition = -1;

        int end = mDatas.size();

        for (int i = 0; i < end; i++) {

            InspectionBean.ItemBean model = mDatas.get(i);
            if ("".equals(model.getItemid()))
                continue;

            if (inspectionName.equals(model.getInspection_name())) {
                if (Integer.parseInt(model.getItemid()) > itemId) {
                    itemId = Integer.parseInt(model.getItemid());
                    retPosition = i;
                }
            }

        }
        return retPosition;
    }

    int getMaxGroupId() {

        int GrpoupId = 0;

        int end = mDatas.size();

        for (int i = 0; i < end; i++) {

            InspectionBean.ItemBean model = mDatas.get(i);
            if ("".equals(model.getGroupid()))
                continue;

            GrpoupId = GrpoupId > Integer.parseInt(model.getGroupid()) ? GrpoupId : Integer.parseInt(model.getGroupid());

        }

        return GrpoupId;

    }

    final void editInspection(final HomeInspectionView view, RecyclerView recycler, int position, String min, String max) {

        if (".".equals(min) || ".".equals(max))
            return;

        if (min.endsWith(".")) {
            min = min.substring(0, min.length() - 1);
        }

        if (min.startsWith(".")) {
            min = min.substring(1, min.length());
        }

        if (max.endsWith(".")) {
            max = max.substring(0, max.length() - 1);
        }

        if (max.startsWith(".")) {
            max = max.substring(1, max.length());
        }

        if (Float.parseFloat(min) >= Float.parseFloat(max)) {
            view.toast("最小参考值不可以大于或等于最大参考值");
            return;
        }

        final InspectionBean.ItemBean itemBean = mDatas.get(position);
        itemBean.setStandard_value(min + "-" + max);
        view.refreshList(recycler);
    }

    final void deleteInspection(final HomeInspectionView view, RecyclerView recycler, final int position) {
        if (null == view || null == recycler || position >= mDatas.size()) {
            return;
        }
        InspectionBean.ItemBean model = mDatas.get(position);
        if ("4".equals(model.getFlag())) {
            mDatas.remove(model);
        } else if (BaseConstant.TWO.equals(model.getAttribute())) {
            model.setItem_value("");
            model.setAttribute(BaseConstant.FOUR);
        } else if (BaseConstant.THREE.equals(model.getAttribute()) || BaseConstant.ZERO.equals(model.getAttribute())) {
            model.setItem_value("");
            model.setAttribute(BaseConstant.ZERO);
        } else {
            ToastUtil.showToast("项目不能删除!");
        }

//        if (BaseConstant.ONE.equals(model.getAttribute()) || BaseConstant.ZERO.equals(model.getAttribute())) {
//            ToastUtil.showToast("系统项目不能删除!");
//        } else if (BaseConstant.TWO.equals(model.getAttribute()) || BaseConstant.THREE.equals(model.getAttribute())) {
//            model.setItem_value("");
//            model.setAttribute(BaseConstant.ZERO);
//        } else {
//            //删除子项
//            mDatas.remove(model);
//        }
        recycler.setTag(INSPECTION_EXIST_DATA);
        view.refreshList(recycler);
    }

    void deletePhoto(final HomeInspectionView view, RecyclerView recycler, final int position) {

        if (null == view || null == recycler || position >= mPhoto.size()) return;

        final String time = getTime(view, recycler);
        if (TextUtils.isEmpty(time)) return;

        final LinkedList<AlbumPhotoBean> list = new LinkedList<>();
        list.addAll(mPhoto);

        final AlbumPhotoBean model = list.get(position);
        list.remove(position);
        for (AlbumPhotoBean temp : list) {
            if (temp.isAdd()) {
                list.remove(temp);
            }
        }

        final HashMap<String, Object> params2 = new HashMap<>();
        params2.put(HttpParams.INSPECTION_DATE, time);
        params2.put(HttpParams.DELPICTURE, model);
        params2.put(HttpParams.JSON_INSPECTION_PICTURE, list);
        final RequestBody params = createParams(params2, HttpParams.DATA_TYPE_414);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().deletePhoto(params);
        request(observable, new OnModelChangeListener() {
            @Override
            public void modelFail() {
                ToastUtil.showToast("删除照片失败");
            }

            @Override
            public void modelSucc() {
                ToastUtil.showToast("删除照片成功");

                recycler.setTag(INSPECTION_NULL.equals(recycler.getTag()) ? INSPECTION_ONLY_PICTURE : INSPECTION_EXIST_DATA);
                mPhoto.remove(model);
                refreshPhoto(view, recycler);
//                // 发送本地广播
//                Intent intent = new Intent("com.quasar.hpatient.image.delete");
//                LocalBroadcastManager.getInstance(BaseApp.getContext()).sendBroadcast(intent);
            }
        });
    }

    void uploadPhoto(final HomeInspectionView view, RecyclerView
            recycler, ArrayList<AlbumPhotoBean> list, int position) {

        if (null == view || null == recycler) return;

        AlbumPhotoBean old = null;
        if (position != -1) {
            old = mPhoto.get(position);
            mPhoto.remove(position);
        }

        final HashMap<String, RequestBody> map = new HashMap<>();

        for (int i = 0; i < list.size(); i++) {
            AlbumPhotoBean album = list.get(i);
            final String imagePath = album.getPicture();
            final File file = new File(imagePath);
            final RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            map.put("file" + i + "\"; filename=\"" + file.getName() + "\"", body);

            HashMap<String, Object> params2 = new HashMap<>();
            params2.put(HttpParams.INSPECTIONDATE, getDate());
            final RequestBody params = createParams(params2, HttpParams.DATA_TYPE_412);
            final Observable observable = HttpClient.getSingleHolder().getHttpService().uploadPhoto(params, map);

            AlbumPhotoBean finalOld = old;
            request(observable, new OnModelAcceptChangeListener<List<AlbumPhotoBean>>() {
                @Override
                public void modelFail() {
                    if (null != finalOld) {
                        mPhoto.add(position, finalOld);
                    }
                }

                @Override
                public void modelSucc(List<AlbumPhotoBean> model) {

                    if (position == -1) {
                        mPhoto.addAll(mPhoto.size() - 1, model);
                    } else {
                        mPhoto.addAll(position, model);
                    }

                    recycler.setTag(INSPECTION_NULL.equals(recycler.getTag()) ? INSPECTION_ONLY_PICTURE : INSPECTION_EXIST_DATA);
                    refreshPhoto(view, recycler);
                }
            });
        }
    }

    final void schemelList(CalendarDialog dialog, String year, String month, String minDay, String maxDay) {

        final HashMap<String, Object> map = new HashMap<>();
        map.put(BEGIN_DATE, BaseApp.getResource().getString(R.string.date_calendar, year, month, minDay));
        map.put(END_DATE, BaseApp.getResource().getString(R.string.date_calendar, year, month, maxDay));

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_4_10);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().schemeList(params);

        request(observable, new OnModelAcceptChangeListener<List<CalendarBean>>() {
            @Override
            public void modelSucc(List<CalendarBean> list) {
                dialog.getCalendarView().setScheme(list);
            }
        });
    }

    final void setEvent(HomeInspectionView view, RecyclerView recycler, List<InspectionBean.EventBean> list, boolean callback) {

        if (callback && (null == list || list.isEmpty()))
            return;

        final RecyclerView.Adapter recyclerAdapter = recycler.getAdapter();
        if (null == recyclerAdapter || !(recyclerAdapter instanceof BaseCommonAdapter))
            return;

        final BaseCommonAdapter adapter = (BaseCommonAdapter) recyclerAdapter;
        final LinearLayout head = adapter.getHead();
        final TextView text = head.findViewById(R.id.home_inspection_event);
        if (null == text) return;

        final boolean isNull = (null == list || list.isEmpty());
        text.setVisibility(isNull ? View.GONE : View.VISIBLE);
        if (isNull) return;

        text.setText(list.get(0).getHints());
        text.setOnClickListener(v -> view.showEvent("事件详情", list));
    }

    final void setSuggest(HomeInspectionView view, RecyclerView recycler, List<InspectionBean.SuggestBean> suggestList) {

        final RecyclerView.Adapter recyclerAdapter = recycler.getAdapter();
        if (null == recyclerAdapter || !(recyclerAdapter instanceof BaseCommonAdapter))
            return;

        final BaseCommonAdapter adapter = (BaseCommonAdapter) recyclerAdapter;
        final LinearLayout head = adapter.getHead();

        final TextView suggest = head.findViewById(R.id.home_inspection_suggest);
        if (null != suggest) {
            final boolean isNull = (null == suggestList || suggestList.isEmpty());
            suggest.setVisibility(isNull ? View.GONE : View.VISIBLE);
            if (!isNull) {
                suggest.setText(suggestList.get(0).getHints());
                suggest.setOnClickListener(v -> view.showList(suggestList));
            }
        }
    }

    final void setTimestap(HomeInspectionView view, RecyclerView recycler, boolean tag) {

        final RecyclerView.Adapter recyclerAdapter = recycler.getAdapter();
        if (null == recyclerAdapter || !(recyclerAdapter instanceof BaseCommonAdapter))
            return;

        final BaseCommonAdapter adapter = (BaseCommonAdapter) recyclerAdapter;
        final LinearLayout head = adapter.getHead();

        final ImageView image = head.findViewById(R.id.home_inspection_tag);
        if (null != image) {
            image.setVisibility(tag ? View.VISIBLE : View.GONE);
        }
    }

    final void setDiagnose(HomeInspectionView view, RecyclerView recycler, List<InspectionBean.DiagnoseBean> diagnoseList) {

        final RecyclerView.Adapter recyclerAdapter = recycler.getAdapter();
        if (null == recyclerAdapter || !(recyclerAdapter instanceof BaseCommonAdapter))
            return;

        final BaseCommonAdapter adapter = (BaseCommonAdapter) recyclerAdapter;
        final LinearLayout head = adapter.getHead();
        final TextView diagnose = head.findViewById(R.id.home_inspection_diagnose);
        if (null != diagnose) {
            final boolean isNull = (null == diagnoseList || diagnoseList.isEmpty());
            diagnose.setVisibility(isNull ? View.GONE : View.VISIBLE);
            if (!isNull) {
                diagnose.setText(diagnoseList.get(0).getHints());
                diagnose.setOnClickListener(v -> view.showList(diagnoseList));
            }
        }
    }

    List<InspectionBean.DoctorBean> getDoctorList() {
        return mDoctor;
    }

    private final void refreshPhoto(HomeInspectionView view, RecyclerView recycler) {

        if (null == view || null == recycler) return;

        final RecyclerView photo = view.getHead(recycler, R.id.home_inspection_picture);
        if (null == photo) return;

        final RecyclerView.Adapter adapter1 = photo.getAdapter();
        adapter1.notifyDataSetChanged();
        photo.smoothScrollToPosition(adapter1.getItemCount() - 1);
    }

    final void setTime(HomeInspectionView view, RecyclerView recycler, String datetime) {

        if (null == recycler)
            return;

        if (TextUtils.isEmpty(datetime)) {
            datetime = "日期：" + getDate();
        } else {
            datetime = "日期：" + datetime;
        }

        final TextView text = view.getHead(recycler, R.id.home_inspection_time);
        if (null == text) return;
        text.setText(datetime);
    }

    public String getTime(HomeInspectionView view, RecyclerView recycler) {

        final TextView text = view.getHead(recycler, R.id.home_inspection_time);
        final String str = text.getText().toString();
        return str.substring(3, str.length());
    }

    @Override
    public void recycler() {
    }
}
